import os
import subprocess
import time

VIRTUAL_IP = "192.168.0.100"  # Replace with your VIP
REAL_IP = "192.168.0.118"  # Real IP address
INTERFACE = "Ethernet"         # Replace with your network interface
UBUNTU_HOST_IP = "192.168.0.147" # Ubuntu host IP
CHECK_INTERVAL = 5             # Check interval in seconds

# Assign VIP
def assign_vip():
    try:
        subprocess.run(f"netsh interface ip add address \"{INTERFACE}\" {VIRTUAL_IP} 255.255.255.0", check=True, shell=True)
        print(f"Assigned VIP {VIRTUAL_IP}")
    except subprocess.CalledProcessError as e:
        print(f"Error assigning VIP: {e}")


# Remove VIP
def remove_vip():
    try:
        subprocess.run(f"netsh interface ip delete address \"{INTERFACE}\" {VIRTUAL_IP}", check=True, shell=True)
        print(f"Removed VIP {VIRTUAL_IP}")
        subprocess.run(f"netsh interface ip add address \"{INTERFACE}\" {REAL_IP} 255.255.255.0", check=True, shell=True)
        print(f"Real IP {REAL_IP}")
    except subprocess.CalledProcessError as e:
        print(f"Error removing VIP: {e}")

# Check if Ubuntu host is alive
def is_ubuntu_alive():
    response = subprocess.run(f"ping -c 1 {UBUNTU_HOST_IP}", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    print(response.stdout.lower())
    if "unreachable" in f"{response.stdout.lower()}" or "timed out" in f"{response.stdout.lower()}":
        return False
    return response.returncode == 0

# Standby server logic
def standby_logic():
    vip_assigned = False
    while True:
        if is_ubuntu_alive():
            print("Ubuntu host is online.")
            if vip_assigned:
                print("Releasing VIP as Ubuntu host is active.")
                remove_vip()
                vip_assigned = False
        else:
            print("Ubuntu host is offline.")
            if not vip_assigned:
                print("Taking over VIP.")
                assign_vip()
                vip_assigned = True
        time.sleep(CHECK_INTERVAL)

if __name__ == "__main__":
    standby_logic()